<?php


namespace App\Library\Util;


use App\Consts\CacheConst;
use App\Library\Lock\RedLock;
use Illuminate\Support\Facades\Config;

class LockUtil
{

    /**
     * 锁操作
     *
     * @param $key
     * @param int $time
     * @return bool
     */
    public static function uriLock($key, $time = 180)
    {
        $ttl = $time * 1000;
        $cacheKey = sprintf(CacheConst::URI_LOCKED, $key);

        // 新锁
        $redlocknew = new RedLock(self::getServers(), 0, 1);
        $newres = $redlocknew->lock($cacheKey, 1, $ttl);
        $redlocknew->clear();

        return false === $newres;
    }

    private static function getServers()
    {
        $config = Config::get('database.redis.cache');
        $servers = [
            [
                $config['host'],
                $config['port'],
                $config['timeout'],
                $config['password'],
            ]
        ];
        return $servers;
    }

    //锁操作
    public static function lock($cacheKey, $time = 180)
    {
        $ttl = $time * 1000;

        // 新锁
        $redlocknew = new RedLock(self::getServers(), 0, 1);

        $newres = $redlocknew->lock($cacheKey, 1, $ttl);
        $redlocknew->clear();

        return false === $newres;
    }

    /**
     * 解锁操作
     *
     * @param $key
     * @return bool
     */
    public static function unLock($key)
    {
        $cacheKey = sprintf(CacheConst::REPEAT_LOCKED, $key);

        $redLock = new RedLock(self::getServers(), 0, 1);

        $redLock->unlock($cacheKey, 1);
        $redLock->clear();

        return true;
    }
}
